﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AES小工具
{
    public partial class FrmMqtt : Form
    {
        public FrmMqtt()
        {
            InitializeComponent();
        }

        private void btnDecode_Click(object sender, EventArgs e)
        {
            string deCodeTxt = tbDecode.Text.Trim();
            string password = tbPassword.Text.Trim();

            //byte[] bytes = null;
            //if (deCodeTxt.Contains(" "))
            //{
            //    String[] bytesStr = deCodeTxt.Split(' ');
            //    int len = bytesStr.Length;
            //    bytes = new byte[len];
            //    for (int i = 0; i < len; i++)
            //    {
            //        bytes[i] = Convert.ToByte(bytesStr[i],16);
            //    }
            //}
            //else { 
            //    if(deCodeTxt.Length % 2 > 0) {
            //        MessageBox.Show("数据有误!");
            //        return;
            //    }
            //    char[] chars = deCodeTxt.ToCharArray();
            //    int len = chars.Length/2;
            //    bytes = new byte[len];
            //    for(int i = 0;i < len; i++)
            //    {
            //        string hexStr = chars[2 * i].ToString() + chars[2 * i + 1].ToString();
            //        bytes[i] = Convert.ToByte(hexStr, 16);
            //    }
            //}

            //byte[] bytes1 = AESHelper.AESDecrypt(bytes, password);
            //string txt = Encoding.GetEncoding("GB2312").GetString(bytes1);

            tbEncode.Text = logDecode(deCodeTxt,password);
        }

        private string logDecode(string deCodeTxt, string password) {
            byte[] bytes = null;
            if (deCodeTxt.Contains(" "))
            {
                String[] bytesStr = deCodeTxt.Split(' ');
                int len = bytesStr.Length;
                bytes = new byte[len];
                for (int i = 0; i < len; i++)
                {
                    bytes[i] = Convert.ToByte(bytesStr[i], 16);
                }
            }
            else
            {
                if (deCodeTxt.Length % 2 > 0)
                {
                    MessageBox.Show("数据有误!");
                    return "";
                }
                char[] chars = deCodeTxt.ToCharArray();
                int len = chars.Length / 2;
                bytes = new byte[len];
                for (int i = 0; i < len; i++)
                {
                    string hexStr = chars[2 * i].ToString() + chars[2 * i + 1].ToString();
                    bytes[i] = Convert.ToByte(hexStr, 16);
                }
            }

            byte[] bytes1 = null;
            try {
                bytes1 = AESHelper.AESDecrypt(bytes, password);
                string txt = Encoding.GetEncoding("GB2312").GetString(bytes1);
                return txt;
            }
            catch { }finally { }
            return "hex_code  " + deCodeTxt;
        }

        private void btnEncode_Click(object sender, EventArgs e)
        {
            string txt = tbEncode.Text;
            string password = tbPassword.Text.Trim();
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(txt);
            byte[] bytes1 = AESHelper.AESEncrypt(bytes, password);
            string hexStr = "";
            for(int i = 0; i < bytes1.Length; i++) {

                if (cbBlank.Checked && !hexStr.Equals(""))
                    hexStr += " ";
                hexStr += bytes1[i].ToString("X2");
            }
            tbDecode.Text = hexStr;
        }

        private void btnDecodeLog_Click(object sender, EventArgs e)
        {
            string password = tbPassword.Text.Trim();
            string uidTxt = tbUid.Text.Trim();
            //选择文件
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*log*)|*.log*"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() != DialogResult.OK) {
                Console.WriteLine("没有选择文件");
                return;
            }
            
            string filePath = fileDialog.FileName;//返回文件的完整路径
            DateTime startDt = DateTime.Now;
            //读取文件
            string[] logs = System.IO.File.ReadAllLines(filePath);            
            List<string> txts = new List<string>();
            //解密
            foreach(string log in logs)
            {
                if (uidTxt != null || uidTxt.Length > 5) {
                    if (!log.Contains(uidTxt))
                        continue;
                }
                string[] strs = log.Split(new String[] { " [PUBLISH] ", "topic:", ", payload: " },StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strs)
                {
                    Console.WriteLine(str);
                }
                if(strs.Length < 3) {
                    continue;
                }
                //提取时间
                string timeStr = strs[0];
                //提取主题
                string topic = strs[2];
                //提取数据并解密
                string cmdTxt = logDecode(strs[3], password);

                string txt = timeStr + "  " + topic + "\r\n" + cmdTxt;
                txts.Add(txt); 
            }
            //创建新的文件路径
            string[] pathStrs = filePath.Split('\\');
            string newFilePath = "";
            foreach(string path in pathStrs)
            {
                if (!newFilePath.Equals(""))
                    newFilePath += "\\";
                if (path.Contains("log")) {
                    DateTime dt = DateTime.Now;
                    newFilePath += dt.ToString("yyyyMMddHHmmssfff") + "_"  + uidTxt + ".txt";
                    continue;
                }
                newFilePath += path;
            }

            //回写文件
            System.IO.File.WriteAllLines(newFilePath,txts.ToArray());
            if (!cbIsShowDeCode.Checked) {
                MessageBox.Show(string.Format( "解密完成，用时{0}秒!",calcSec(startDt).ToString()));
                return;
            }
                
            tbDecode.Text = "";
            foreach (string txt in txts) { 
                tbDecode.Text += txt;
            }
            MessageBox.Show(string.Format("解密完成，用时{0}秒!", calcSec(startDt).ToString()));
        }

        private  double calcSec(DateTime dt)
        {
            TimeSpan ts = DateTime.Now - dt;
            return ts.TotalSeconds;
        }
        
        
    }
}
